<template>
  <div class="scroll-y columnSS" style="gap: 10px;">
    <!--操作-->
    <div class="rowBS" style="width: 100%">
      <div>
        <el-button v-if="multipleSelection.length > 0" type="danger" @click="onClickBtnBatchDel">
          <el-icon>
            <Delete style="vertical-align: middle" />
          </el-icon>
          <span style="vertical-align: middle">删除</span>
        </el-button>
        <el-button plain type="primary" @click="getTableListData">
          <el-icon>
            <Refresh style="vertical-align: middle" />
          </el-icon>
          <span style="vertical-align: middle">刷新</span>
        </el-button>
      </div>
      <el-button type="primary" @click="onClickBtnAdd">
        <el-icon style="vertical-align: middle">
          <FolderAdd />
        </el-icon>
        <span style="vertical-align: middle">增加</span>
      </el-button>
    </div>
    <div class="rowSS" style="background-color: #e3e3e3; width: 100%; padding: 10px; gap: 10px;">
      <!--条件搜索-->
      <el-form ref="refSearchForm" :inline="true">
        <el-form-item style="margin: 0" label-width="0px" label="" prop="name" label-position="left">
          <el-input v-model="searchForm.name" class="widthPx-150" placeholder="角色" />
        </el-form-item>
        <el-form-item style="margin: 0" label-width="50px" label="slug:" prop="slug" label-position="left">
          <el-input v-model="searchForm.slug" class="widthPx-150" placeholder="KEY" />
        </el-form-item>
      </el-form>
      <!--查询按钮-->
      <el-button type="success" @click="searchBtnClick">查询</el-button>
    </div>
    <!--表格和分页-->
    <el-table
      id="resetElementDialog"
      ref="refTable"
      :height="`calc(100vh - ${settings.delWindowHeight})`"
      border
      :data="tableListData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column align="center" prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色" />
      <el-table-column prop="slug" label="KEY" />
      <el-table-column label="菜单">
        <template #default="{ row }">
          <el-tree default-expand-all :data="row.menuTree" :props="{ label: 'title' }" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createdAt" label="创建时间" width="110" />
      <el-table-column align="center" prop="updatedAt" label="更新时间" width="110" />
      <!--点击操作-->
      <el-table-column fixed="right" align="center" label="操作" width="180">
        <template #default="{ row }">
          <el-button :disabled="row.id === 1" text type="info" size="small" @click="onClickTableRowEdit(row)">编辑
          </el-button>
          <el-button :disabled="row.id === 1" text type="danger" size="small" @click="tableDelClick(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="block columnCC" style="width: 100%">
      <el-pagination
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <RoleForm
      v-if="showFrom" ref="refRoleForm"
      :tree-data="menuTreeData"
      @hide-comp="handleHideForm"
      @form-sub="getTableListData" />
  </div>
</template>
<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import { Delete, FolderAdd, Refresh } from "@element-plus/icons-vue"
import { elConfirm, elMessage } from '@/hooks/use-element'
import { useTable } from '@/hooks/use-table'
import { delRoleReq, getMenuTreeReq, getRoleReq } from "@/api/setting"
import settings from "@/settings"
import RoleForm from "./RoleForm.vue"

onMounted(() => {
  getTableListData();
  getMenuTreeData();
});

const refTable = ref(null);

const searchForm = reactive({
  id: "",
  name: "",
  slug: ""
});
//
const onClickBtnAdd = () => {
  showFrom.value = true;
  nextTick(() => {
    refRoleForm.value.showModal();
  });
};

const searchBtnClick = () => {
  pageNum.value = 1;
  getTableListData();
};

let getTableListData = () => {
  const data = Object.assign(searchForm, {
    page: pageNum.value,
    pageSize: pageSize.value
  });
  Object.keys(data).forEach((fItem) => {
    if (data[fItem] === "" || data[fItem] === null || data[fItem] === undefined) delete data[fItem];
  });
  getRoleReq(data).then(res => {
    total.value = res.data.total;
    res.data.list.forEach(v => {
      v.menuTree = _list2tree(v.menus || []);
    });
    tableListData.value = res.data.list;
  });
};

let {
  pageNum,
  pageSize,
  total,
  tableListData,
  multipleSelection,
  handleSelectionChange,
  handleCurrentChange,
  handleSizeChange,
} = useTable(getTableListData)

const onClickTableRowEdit = (row) => {
  showFrom.value = true;
  nextTick(() => {
    refRoleForm.value.showModal(row.id, row);
  });
};

const tableDelClick = (row) => {
  elConfirm("确定", `您确定要删除【${row.name}】吗？`).then(() => {
    delRoleReq([row.id]).then(() => {
      getTableListData();
      elMessage(`【${row.name}】删除成功`);
    });
  }).catch(() => {
  });
};

const onClickBtnBatchDel = () => {
  // console.log(refTable.value.getSelectionRows());
  const names: string[] = [];
  const ids: number[] = [];
  multipleSelection.value.forEach(v => {
    names.push(v.name)
    ids.push(v.id)
  })
  elConfirm("确定", `您确定要删除【${names.join('、')}】吗？`).then(() => {
    delRoleReq(ids).then(() => {
      getTableListData();
      elMessage(`【${names.join('、')}】删除成功`);
    });
  }).catch(() => {
  });
};

//
let showFrom = ref(false);
const refRoleForm = ref();
const menuTreeData = ref([]);
const getMenuTreeData = () => {
  getMenuTreeReq().then(res => {
    menuTreeData.value = res.data.tree;
  });
};
const handleHideForm = () => {
  showFrom.value = false;
};

//
function _list2tree(list) {
  const map = {}
  const treeData: any[] = []
  for (const [i, element] of list.entries()) {
    map[element.id] = i;
    element.children = [];
  }
  for (let i = 0; i < list.length; i += 1) {
    const node = list[i];
    if (node.pid && list[map[node.pid]]) {
      list[map[node.pid]].children.push(node);
    } else {
      treeData.push(node);
    }
  }
  return treeData;
}
</script>
